<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Search - "{{ search_text }}" - Results</title>
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <meta name="description" content="results of {{ project }}">
    <meta name="author" content="binux">
    <link href="{{ url_for('cdn', path='twitter-bootstrap/3.1.1/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static', filename='result.css') }}" rel="stylesheet">

    <script src="{{ url_for('cdn', path='jquery/1.11.0/jquery.min.js') }}"></script>
    <script src="{{ url_for('cdn', path='twitter-bootstrap/3.1.1/js/bootstrap.min.js') }}"></script>
  </head>

  <body>
    <div class="top-bar">
      <h1>Search keywords "{{ search_text }}"，{{ count }} items found</h1>
      <div class="btn-group">
        <input type="button" data-toggle="modal" data-target="#delete-search-modal" value="Delete selected items" />
        <div class="modal fade" id="delete-search-modal">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Delete checked Results</h4>
              </div>
              <form class="form-horizontal" method="DELETE">
                <div class="modal-body">
                  <label class="control-label" for="result-name">Are you sure to delete checked results ?</label>
                </div>
                <div class="modal-footer" >
                  <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                  <button type="button" class="btn btn-primary" data-dismiss="modal" onclick="javascript:delete_checked_results(this)">Ok</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
    # set common_fields, results = result_formater(results)
    <table class="table table-condensed table-striped">
      <thead>
        <th>
          <input name="select_all" id="id_select_all"  autocomplete="off" type="checkbox" value="" onclick="checkAll(this)"/>
        </th>
        <th>url</th>
        <th></th>
        # for field in common_fields|sort
        <th>
          {{ field }}
        </th>
        # endfor
        <th>
          ...
        </th>
        <th>actions</th>
      </thead>
      <tbody>
        # for result in results
        <tr>
          <td>
            <input name="select_one" id="{{ project }}:{{ result.taskid }}" autocomplete="off" type="checkbox" value="" />
          </td>
          <td>
            <div>
              <a class=url href="/task/{{ project }}:{{ result.taskid }}" target=_blank>{{ result.url }}</a>
            </div>
            {% if result.get('file', '') and result.url.endswith('.pdf')  %}
            <div data-name="{{ result.taskid }}" data-value="{{ result.file }}">
              <button id="prev-{{ result.taskid }}" onClick="onPrevPage(this)">Previous</button>
              <button id="next-{{ result.taskid }}" onClick="onNextPage(this)">Next</button>
              &nbsp; &nbsp;
              <span>Page: <span id="page_num-{{ result.taskid }}">1</span> / <span id="page_count-{{ result.taskid }}">15</span></span>
            </div>
            <div>
              <canvas id="canvas-{{ result.taskid }}" value="{{ result.file }}" style="border:1px  solid black"></canvas>
            </div>
            {% endif %}
          </td>
          <td>
            <a class=open-url href="{{ result.url }}" target="_blank"><span class="glyphicon glyphicon-new-window"></span></a>
          </td>
          # for field in common_fields|sort
          <td>{{ json.dumps(result.result_formated[field], ensure_ascii=False) | truncate(100, True) }}</td>
          # endfor
          <td>
            {{ json.dumps(result.others, ensure_ascii=False) | truncate(100, True) }}
          </td>
          <td>
              # if config.scheduler_rpc is not none:
              <button class="result-delete btn btn-default btn-xs" data-toggle="modal" data-target="#delete-result-modal{{ result.taskid }}">Delete</button>
              # endif
              <div class="modal fade" id="delete-result-modal{{ result.taskid }}">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                      <h4 class="modal-title">Delete Result</h4>
                    </div>
                    <form class="form-horizontal" method="DELETE">
                      <div class="modal-body">
                        <label class="control-label" for="result-name">Are you sure to delete this result ?</label>
                      </div>
                      <div class="modal-footer" data-name="{{ project }}:{{ result.taskid }}">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" data-dismiss="modal" onClick="delete_result(this)">Ok</button>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
          </td>
          <td>
              # if config.scheduler_rpc is not none:
              <button class="result-modify btn btn-default btn-xs" data-toggle="modal" data-target="#result-modify-modal{{ result.taskid }}">Modify</button>
              # endif
              <div class="modal fade" id="result-modify-modal{{ result.taskid }}">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                      <h4 class="modal-title">Modify This Result</h4>
                    </div>
                    <form class="form-horizontal" method="PUT">
                      <div class="modal-body">
                        # for field in common_fields|sort
                        <div class="form-group">
                          <label class="col-sm-3 control-label" for="result-{{ field }}">{{ field }}</label>
                          <div class="col-sm-9">
                            <input class="form-control" type="text" name="result-{{ field }}" value="{{ json.dumps(result.result_formated[field], ensure_ascii=False) }}">
                          </div>
                        </div>
                        # endfor
                      </div>
                      <div class="modal-footer" data-name="{{ project }}:{{ result.taskid }}">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" data-dismiss="modal" onClick="modify_result(this)">Ok</button>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
          </td>

        </tr>
        # endfor
      </tbody>
    </table>

    <script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
    <script id="script" type="text/javascript">
      var canvas_ids = document.getElementsByTagName("canvas"),
          resultid2pdf = {};
      console.log(canvas_ids)
      max = canvas_ids.length
      var i=0
      function run(){
        var canvas_id = canvas_ids[i].getAttribute("id"),
            canvas_file = canvas_ids[i].getAttribute("value"),
            resultid = canvas_id.split('-')[1],
            canvas = document.getElementById(canvas_id),
            context = canvas.getContext('2d'),
            pdfData = atob(canvas_file);
        PDFJS.workerSrc = 'https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.worker.js';
        PDFJS.getDocument({data: pdfData}).then(function getPdfHelloWorld(pdf) {
          // Fetch the first page.
          resultid2pdf[resultid] = pdf;
          document.getElementById('page_count-'+resultid).textContent = pdf.numPages;
          pdf.getPage(1).then(function getPageHelloWorld(page) {
            var scale = 1;
            var viewport = page.getViewport(scale);
            var viewport = page.getViewport(600/viewport.width);
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            var renderContext = {
              canvasContext: context,
              viewport: viewport
            };
            page.render(renderContext);
          });
        });
        i++
      }
      if(i>max){clearInterval(interval)}
      var interval=setInterval(run,1)
    </script>

    <script type="text/javascript">
      var pdfDoc = null,
          pageRendering = false,
          pageNumPending = null,
          canvas = null,
          ctx = null,
          resultid = null,
          pageNum = 1;
      function onNextPage(self) {
        resultid = $(self).parent().data("name");
        pdfDoc = resultid2pdf[resultid];
        if (pdfDoc == null){
          /**
           * Asynchronously downloads PDF.
           */
          PDFJS.getDocument({data: pdfData}).then(function (pdfDoc_) {
            pdfDoc = pdfDoc_;
            resultid2pdf[resultid]=pdfDoc;
          });
        }
        pageNum = document.getElementById('page_num-'+resultid).textContent
        console.log(pageNum)
        canvas = document.getElementById('canvas-'+resultid);
        ctx = canvas.getContext('2d');
        if (pageNum >= pdfDoc.numPages) {
          return;
        }
        pageNum++;
        queueRenderPage(pageNum);
      }

      function onPrevPage(self) {
        resultid = $(self).parent().data("name");
        pdfDoc = resultid2pdf[resultid];
        if (pdfDoc == null){
          /**
           * Asynchronously downloads PDF.
           */
          PDFJS.getDocument({data: pdfData}).then(function (pdfDoc_) {
            pdfDoc = pdfDoc_;
          });
        }
        pageNum = document.getElementById('page_num-'+resultid).textContent
        canvas = document.getElementById('canvas-'+resultid);
        ctx = canvas.getContext('2d');
        if (pageNum <= 1) {
          return;
        }
        pageNum--;
        queueRenderPage(pageNum);
      }

      function queueRenderPage(num) {
        if (pageRendering) {
          pageNumPending = num;
        } else {
          renderPage(num);
        }
      }

      function renderPage(num) {
        pageRendering = true;
        // Using promise to fetch the page
        pdfDoc.getPage(num).then(function(page) {
          var scale = 1;
          var viewport = page.getViewport(scale);
          var viewport = page.getViewport(600/viewport.width);
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          // Render PDF page into canvas context
          var renderContext = {
            canvasContext: ctx,
            viewport: viewport
          };
          var renderTask = page.render(renderContext);

          // Wait for rendering to finish
          renderTask.promise.then(function () {
            pageRendering = false;
            if (pageNumPending !== null) {
              // New page rendering is pending
              renderPage(pageNumPending);
              pageNumPending = null;
            }
          });
        });

        // Update page counters
        document.getElementById('page_num-'+resultid).textContent = pageNum;
      }

	</script>

    <script type="text/javascript">
		function delete_checked_results(self) {
          var inputs = document.getElementsByTagName("input");
          var all_project_taskid=""
          for(var i=1;i<inputs.length;i++) {
		      if(inputs[i].getAttribute("type") == "checkbox" && inputs[i].getAttribute("name") == "select_one"
		                    && inputs[i].checked == true) {
		        console.log("delete_checked_results, select_one is checked")
		        all_project_taskid += inputs[i].getAttribute("id") + ","
		      }
		  }
		  console.log(all_project_taskid)
		  $.ajax({
			type: "DELETE",
			url: '/action_search_result',
			data: {
			  all_project_taskid: all_project_taskid
			},
			success: function(data) {
			  console.log(data);
			  document.location.reload();
			},
			error: function(e) {
			  console.log(location.href);
			  document.location.reload();
			}
		  });

		};
	</script>

    <script type="text/javascript">
		function search(self) {
		  var search_text=document.getElementById("searchvalue").value;
          console.log(search_text);
		  $.ajax({
			type: "POST",
			url: '/search_result',
			data: {
			  search_text: search_text
			},
			success: function(data) {
			  console.log(data);
			},
			error: function(e) {
			  console.log(location.href);
			}
		  });
		};
	</script>

    <script type="text/javascript">
		function checkAll(self) {
		  var inputs = document.getElementsByTagName("input");
		  var id_select_all = document.getElementById("id_select_all")
		  if(id_select_all.checked == true) {
		    console.log("select_all is checked")
		    for(var i=1;i<inputs.length;i++) {
		      if(inputs[i].getAttribute("type") == "checkbox" && inputs[i].getAttribute("name") == "select_one") {
		        inputs[i].checked = true;
		        console.log("select_one is checked")
		      }
		    }
		  }else{
		    console.log("select_all is not checked")
		    for(var i=0;i<inputs.length;i++) {
		      if(inputs[i].getAttribute("type") == "checkbox" && inputs[i].getAttribute("name") == "select_one") {
		        inputs[i].checked = false;
		        console.log("select_one is not checked")
		      }
		    }
          }

		};
	</script>

    <script type="text/javascript">
		function delete_result(self) {
		  var project_taskid = $(self).parent().data("name");
		  console.log(project_taskid);
		  $.ajax({
			type: "DELETE",
			url: '/action_result',
			data: {
			  project_taskid: project_taskid
			},
			success: function(data) {
			  console.log(data);
			  document.location.reload();
			},
			error: function(e) {
			  console.log(location.href);
			  document.location.reload();
			}
		  });
		};
	</script>

    <script type="text/javascript">
        function modify_result(self) {
          var project_taskid = $(self).parent().data("name");
          var arr = $(self).parents('form').serializeArray();
          console.log($.param(arr)+"&project_taskid="+project_taskid);
          $.ajax({
            type: "PUT",
            url: '/action_result_modify',
            data: $.param(arr)+"&project_taskid="+project_taskid,
            success: function(data) {
              console.log(data);
              document.location.reload();
            },
            error: function(e) {
              console.log(e);
              document.location.reload();
            }
          });
        };
    </script>


    <div class="pagination-wrap" >
      <ul class="pagination">
        # set current_page = int(offset/limit) + (1 if offset%limit else 0)
        # set total_page = int(count/limit) + (1 if count%limit else 0)
        <li class="{{ "disabled" if current_page - 1 <= 0 else "" }}">
          <a href="{% if current_page>1 %}/search_result?project={{ project }}&search_text={{ search_text }}&offset={{ (current_page-1)*limit }}&limit={{ limit }}{% endif %}">&laquo;</a>
        </li>
        # set prev = 0
        # for i in range(0, total_page):
        # if abs(i-0) < 2 or abs(i-total_page) < 3 or -2 < i-current_page < 5:
          # set prev = i
          <li class="{% if i == current_page %}active{% endif %}">
            <a href="/search_result?project={{ project }}&offset={{ i*limit }}&search_text={{ search_text }}&limit={{ limit }}">{{ i + 1 }}</a>
          </li>
        # elif prev == i-1:
        <li class="disabled"><a>…</a></li>
        # endif
        # endfor
        <li class="{{ "disabled" if current_page + 1 >= total_page else "" }}">
          <a href="{% if current_page+1<total_page %}/search_result?project={{ project }}&search_text={{ search_text }}&offset={{ (current_page+1)*limit }}&limit={{ limit }}{% endif %}">&raquo;</a>
        </li>
      </ul>
    </div>
  </body>
</html>
